package com.vtuzx.kingdee.xqc_core.service.impl;

import com.vtuzx.core.VtuzxException;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.constant.IVtuzxConst;
import com.vtuzx.core.utils.VtuzxUtil;
import com.vtuzx.kingdee.xqc_core.bean.VtuzxArrayList;
import com.vtuzx.kingdee.xqc_core.bean.kingdee.VtuzxKingdeeCloudClient;
import com.vtuzx.kingdee.xqc_core.dao.IntegrationHistoryDao;
import com.vtuzx.kingdee.xqc_core.service.IVtuzxCoreService;
import com.vtuzx.kingdee.xqc_core.service.IVtuzxKingdeeService;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class VtuzxCoreServiceImpl implements IVtuzxCoreService {

    /** Logger */
    private static final Logger _logger = LoggerFactory.getLogger(VtuzxCoreServiceImpl.class);

    @Autowired
    private IVtuzxKingdeeService kingdeeService;

    /** 履历 */
    @Autowired
    private IntegrationHistoryDao integrationHistoryDao;



    /**
     * 同步聚水潭物料
     * @param from 数据获取时间范围
     * @param to 数据获取时间范围
     */
    public void syncMaterial(Date from, Date to) {
        subSyncMaterial(1, 50, from, to);
    }

    private void subSyncMaterial(int pageIndex, int pageSize, Date from, Date to) {
//        _logger.info(String.format("开始同步聚水潭物料, 第%d页", pageIndex));
//        JushuitanAccount account = jushuitanService.getAccount();
//        try {
//            VtuzxMap materialParam = new VtuzxMap();
//            materialParam.append("modified_begin", VtuzxUtil.formatYmdHmsF(from));
//            materialParam.append("modified_end", VtuzxUtil.formatYmdHmsF(to));
//            materialParam.append("page_index", pageIndex);
//            materialParam.append("page_size", pageSize);
//            //聚水潭物料
//            VtuzxMap materialRes = jushuitanService.callApi(account, "sku.query", materialParam);
//            List<Map<String, Object>> datas = VtuzxUtil.getObject(materialRes, "datas");
//            _logger.info(String.format("获取聚水潭物料, 第%d页, 共%d单", pageIndex, datas.size()));
//            VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
//            for (Map<String, Object> data: datas) {
//                try {
//                    VtuzxMap kingdeeMaterialParam = new VtuzxMap();
//                    String name = VtuzxUtil.getString(data, "name");
//                    String skuId = VtuzxUtil.getString(data, "sku_id");
//                    Double costPrice = VtuzxUtil.getDouble(data, "cost_price");
//                    String supplierId = VtuzxUtil.getString(data, "supplier_id");
//                    if (VtuzxUtil.isEmpty(name)) {
//                        name = skuId;
//                    }
//                    if (VtuzxUtil.isEmpty(name) && VtuzxUtil.isEmpty(skuId)) {
//                        return;
//                    }
//                    String properties = VtuzxUtil.getString(data, "properties_value");
//
//                    List<VtuzxMap> materialQuery = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
//                                    "FMATERIALID",
//                                    "FDocumentStatus"
//                            ),
//                            String.format("FNumber = '%s'", skuId), null, 0, 0);
//                    if (!VtuzxUtil.isEmpty(materialQuery)) {
//                        String materialId = VtuzxUtil.getString(materialQuery.get(0), "FMATERIALID");
//                        String fDocumentStatus = VtuzxUtil.getString(materialQuery.get(0), "FDocumentStatus");
//                        VtuzxMap model = new VtuzxMap();
//                        model.append("FCreateOrgId", new VtuzxMap("FNumber", 100))
//                                .append("FName", name)
//                                .append("FNumber", skuId)
//                                .append("F_ora_Base", new VtuzxMap("FNumber", "JST" + supplierId))
//                                .append("SubHeadEntity1", new VtuzxMap("FRefCost", costPrice))
//                                .append("FSpecification", properties)
//                                .append("FMATERIALID", materialId);
//                        kingdeeMaterialParam.append("model", model);
//                        //金蝶物料
//                        List<VtuzxMap> material = kingdeeService.save(client, "BD_MATERIAL", kingdeeMaterialParam);
//                        String materialNumber = VtuzxUtil.getString(material.get(0), "Number");
//                        if (!"C".equals(fDocumentStatus)) {
//                            kingdeeService.submit(client, "BD_MATERIAL", "0", materialNumber);
//                            kingdeeService.audit(client, "BD_MATERIAL", "0", materialNumber);
//                        }
//                    } else {
//                        VtuzxMap model = new VtuzxMap();
//                        model.append("FCreateOrgId", new VtuzxMap("FNumber", 100))
//                                .append("FName", name)
//                                .append("FNumber", skuId)
//                                .append("F_ora_Base", new VtuzxMap("FNumber", "JST" + supplierId))
//                                .append("SubHeadEntity1", new VtuzxMap("FRefCost", costPrice))
//                                .append("FSpecification", properties);
//                        kingdeeMaterialParam.append("model", model);
//                        //金蝶物料
//                        List<VtuzxMap> material = kingdeeService.save(client, "BD_MATERIAL", kingdeeMaterialParam);
//                        String materialNumber = VtuzxUtil.getString(material.get(0), "Number");
//                        kingdeeService.submit(client, "BD_MATERIAL", "0", materialNumber);
//                        kingdeeService.audit(client, "BD_MATERIAL", "0", materialNumber);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//            boolean hasNext = VtuzxUtil.getBoolean(materialRes, "has_next");
//            if (hasNext) {
//                subSyncMaterial(pageIndex + 1, pageSize, from, to);
//                _logger.info(String.format("完成同步聚水潭物料, 第%d页", pageIndex));
//            } else {
//                _logger.info(String.format("完成同步全部聚水潭物料, 共%d页", pageIndex));
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        _logger.info("测试 end!");
    }



    /**
     * 同步聚水潭供应商
     * @param from 数据获取时间范围
     * @param to 数据获取时间范围
     */
    public void syncSupplier(Date from, Date to) {
        subSyncSupplier(1, 50, from, to);
    }

    private void subSyncSupplier(int pageIndex, int pageSize, Date from, Date to) {
//        _logger.info(String.format("开始同步聚水潭供应商, 第%d页", pageIndex));
//        JushuitanAccount account = jushuitanService.getAccount();
//        try {
//            VtuzxMap supplierParam = new VtuzxMap();
//            supplierParam.append("modified_begin", VtuzxUtil.formatYmdHmsF(from));
//            supplierParam.append("modified_end", VtuzxUtil.formatYmdHmsF(to));
//            supplierParam.append("page_index", pageIndex);
//            supplierParam.append("page_size", pageSize);
//            //聚水潭供应商
//            VtuzxMap supplierRes = jushuitanService.callApi(account, "supplier.query", supplierParam);
//            List<Map<String, Object>> datas = VtuzxUtil.getObject(supplierRes, "datas");
//            _logger.info(String.format("获取聚水潭供应商, 第%d页, 共%d单", pageIndex, datas.size()));
//            VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
//
//            for (Map<String, Object> data: datas) {
//                String name = VtuzxUtil.getString(data, "name");
//                String supplierId = VtuzxUtil.getString(data, "supplier_id");
//
//                List<VtuzxMap> supplierQuery = kingdeeService.query(client, "BD_Supplier", new VtuzxArrayList<>(
//                                "FSupplierId",
//                                "FDocumentStatus"
//                        ),
//                        String.format("FNumber = '%s'", supplierId), null, 0, 0);
//                if (!VtuzxUtil.isEmpty(supplierQuery)) {
//                    String fSupplierId = VtuzxUtil.getString(supplierQuery.get(0), "FSupplierId");
//                    String fDocumentStatus = VtuzxUtil.getString(supplierQuery.get(0), "FDocumentStatus");
//                    VtuzxMap kingdeeSupplierParam = new VtuzxMap();
//                    VtuzxMap model = new VtuzxMap();
//                    model.append("FCreateOrgId", new VtuzxMap("FNumber", 100))
//                            .append("FName", name)
//                            .append("FNumber", "JST" + supplierId)
//                            .append("FSupplierId", fSupplierId);
//                    kingdeeSupplierParam.append("model", model);
//                    //金蝶供应商
//                    List<VtuzxMap> supplierList = kingdeeService.save(client, "BD_Supplier", kingdeeSupplierParam);
//                    String supplierNumber = VtuzxUtil.getString(supplierList.get(0), "Number");
//                    if (!"C".equals(fDocumentStatus)) {
//                    kingdeeService.submit(client,"BD_Supplier", "0", supplierNumber);
//                    kingdeeService.audit(client, "BD_Supplier", "0", supplierNumber);
//                    }
//                } else {
//                    VtuzxMap kingdeeSupplierParam = new VtuzxMap();
//                    VtuzxMap model = new VtuzxMap();
//                    model.append("FCreateOrgId", new VtuzxMap("FNumber", 100)).append("FName", name).append("FNumber", "JST" + supplierId);
//                    kingdeeSupplierParam.append("model", model);
//                    //金蝶供应商
//                    List<VtuzxMap> supplierList = kingdeeService.save(client, "BD_Supplier", kingdeeSupplierParam);
//                    String supplierNumber = VtuzxUtil.getString(supplierList.get(0), "Number");
//                    kingdeeService.submit(client,"BD_Supplier", "0", supplierNumber);
//                    kingdeeService.audit(client, "BD_Supplier", "0", supplierNumber);
//                }
//            }
//            boolean hasNext = VtuzxUtil.getBoolean(supplierRes, "has_next");
//            if (hasNext) {
//                _logger.info(String.format("完成同步聚水潭供应商, 第%d页", pageIndex));
//                subSyncSupplier(pageIndex + 1, pageSize, from, to);
//            } else {
//                _logger.info(String.format("完成同步全部聚水潭供应商, 共%d页", pageIndex));
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }



    @Override
    public void syncSaleOutStock(Date from, Date to) {
        subSyncSaleOutStock(1, 50, from, to);
    }

    @Override
    public void syncSaleOutStockHistory(Map<String, Object> history) throws VtuzxException {
//        JushuitanAccount account = jushuitanService.getAccount();
//        VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
//        VtuzxMap kingdeeConfig = kingdeeService.getConfig();
//        Document data = VtuzxUtil.getObject(history, "data");
//        syncKingdeeSaleOutStock(account, client, kingdeeConfig, data);
    }

    /**
     * 同步聚水潭已发货的销售出库单
     * @param pageIndex 页号
     * @param pageSize 页大小
     * @param from 数据获取时间范围
     * @param to 数据获取时间范围
     */
    private void subSyncSaleOutStock(int pageIndex, int pageSize, Date from, Date to) {
//        JushuitanAccount account = jushuitanService.getAccount();
//        try {
//            VtuzxMap saleOutStockParam = new VtuzxMap();
//            saleOutStockParam.append("modified_begin", VtuzxUtil.formatYmdHmsF(from));
//            saleOutStockParam.append("modified_end", VtuzxUtil.formatYmdHmsF(to));
//            saleOutStockParam.append("page_index", pageIndex);
//            saleOutStockParam.append("page_size", pageSize);
//            //聚水潭销售出库单
//            VtuzxMap outStockRes = jushuitanService.callApi(account, "orders.out.simple.query", saleOutStockParam);
//            System.out.println(outStockRes);
//            List<Map<String, Object>> datas = VtuzxUtil.getObject(outStockRes, "datas");
//            VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
//            VtuzxMap kingdeeConfig = kingdeeService.getConfig();
////            for (Map<String, Object> data: datas) {
////                syncKingdeeSaleOutStock(account, client, kingdeeConfig, data);
////            }
////            boolean hasNext = VtuzxUtil.getBoolean(outStockRes, "has_next");
////            if (hasNext) {
////                subSyncSaleOutStock(pageIndex + 1, pageSize, from, to);
////            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }


//    /**
//     * 同步聚水潭已发货的销售出库单
//     * @param account 聚水潭客户端
//     * @param client 金蝶客户端
//     * @param kingdeeConfig 金蝶配置
//     * @param data 聚水潭出库单
//     */
//    private void syncKingdeeSaleOutStock(JushuitanAccount account, VtuzxKingdeeCloudClient client, VtuzxMap kingdeeConfig, Map<String, Object> data) {
//        String orgId = VtuzxUtil.getString(kingdeeConfig, "orgId");
//        // 出库内部单号
//        String oId = VtuzxUtil.getString(data, "o_id");
//        // 销售订单号
//        String soId = VtuzxUtil.getString(data, "so_id");
//
//        Document historyDoc = integrationHistoryDao.findOne(Criteria.where("orderId").is(oId));
//        if (historyDoc == null) historyDoc = new Document("orderId", oId).append("soId", soId);
//        boolean outStockFinish = VtuzxUtil.getBoolean(historyDoc, "outStockFinish");
//        boolean customerFinish = VtuzxUtil.getBoolean(historyDoc, "customerFinish");
//        boolean receiveFinish = VtuzxUtil.getBoolean(historyDoc, "receiveFinish");
//        if (outStockFinish && customerFinish && receiveFinish) return;
//        try {
//            VtuzxMap orderRes = jushuitanService.callApi(account, "orders.single.query", new VtuzxMap("so_ids", new VtuzxArrayList<>(soId)));
//            List<Map<String, Object>> orders = VtuzxUtil.getObject(orderRes, "orders");
//            Map<String, Object> order = orders.get(0);
//            String status = VtuzxUtil.getString(order, "status");
//            List<Map<String, Object>> items = VtuzxUtil.getObject(data, "items");
//            List<Map<String, Object>> pays = VtuzxUtil.getObject(order, "pays");
//
//            if ("Sent".equals(status)) {
//                //采购入库单
//                syncKingdeePurchaseInStock(account, client, kingdeeConfig, data);
//
//
//
//                VtuzxMap kingdeeOutStockParam = new VtuzxMap();
//                List<VtuzxMap> saleOutStock = kingdeeService.query(client, "SAL_OUTSTOCK", new VtuzxArrayList<>(
//                                "FID",
//                                "FDocumentStatus"
//                        ),
//                        String.format("FSHOPNUMBER = '%s'", oId), null, 0, 0);
//                if (!VtuzxUtil.isEmpty(saleOutStock)) {
//                    String fid = VtuzxUtil.getString(saleOutStock.get(0), "FID");
//                    String fDocumentStatus = VtuzxUtil.getString(saleOutStock.get(0), "FDocumentStatus");
//                    // 销售出库单
//                    Map<String, Object> model = new LinkedHashMap<>();
//                    List<VtuzxMap> FEntity = new ArrayList<>();
//                    for (Map<String, Object> item : items) {
//                        VtuzxMap detailed = new VtuzxMap();
//                        String skuId = VtuzxUtil.getString(item, "sku_id");
//                        double qty = VtuzxUtil.getDouble(item, "qty");
//                        if (qty == 0) {
//                            saveHistory(historyDoc, data, "outStock", true, "出库数量为0，暂存为成功");
//                            return;
//                        }
//                        List<VtuzxMap> materialQuery = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
//                                        "FMATERIALID",
//                                        "FDocumentStatus",
//                                        "F_ora_Base.FNumber",
//                                        "FRefCost"
//                                ),
//                                String.format("FNumber = '%s'", skuId), null, 0, 0);
//                        if (VtuzxUtil.isEmpty(materialQuery)) return;
//                        String supplierId = VtuzxUtil.getString(materialQuery.get(0), "F_ora_Base.FNumber");
//                        String costPrice = VtuzxUtil.getString(materialQuery.get(0), "FRefCost");
//
//                        detailed.append("FMaterialId", new VtuzxMap("FNumber", skuId))
//                                .append("FUnitID", new VtuzxMap("FNumber", "Pcs"))
//                                .append("FRealQty", qty)
//                                .append("FStockID", new VtuzxMap("FNumber", "CK001"))
//                                .append("F_ora_gys", new VtuzxMap("FNumber", supplierId))
//                                .append("F_ora_PURPrice", costPrice);
//                        FEntity.add(detailed);
//                    }
//                    model.put("FCreateOrgId", new VtuzxMap("FNumber", orgId));
//                    model.put("FSaleOrgId", new VtuzxMap("FNumber", orgId));
//                    model.put("FDate", VtuzxUtil.formatYmdF(new Date()));
//                    model.put("FStockOrgId", new VtuzxMap("FNumber", orgId));
//                    model.put("FCustomerID", new VtuzxMap("FNumber", "001"));
//                    model.put("FBillTypeID", new VtuzxMap("FNumber", "XSCKD01_SYS"));
//                    model.put("FSHOPNUMBER", oId);
//                    model.put("FID", fid);
//                    model.put("FEntity", FEntity);
////                model.put("SubHeadEntity", new VtuzxMap("FExchangeRate", 1));
//
//                    kingdeeOutStockParam.append("model", model);
//                    List<VtuzxMap> outStock = kingdeeService.save(client, "SAL_OUTSTOCK", kingdeeOutStockParam);
//                    String outStockNumber = VtuzxUtil.getString(outStock.get(0), "Number");
//                    if (!"C".equals(fDocumentStatus)) {
//                        kingdeeService.submit(client,"SAL_OUTSTOCK", "0", outStockNumber);
//                        kingdeeService.audit(client, "SAL_OUTSTOCK", "0", outStockNumber, "STK_InvCheckResult");
//                    }
//                    // 履历设定
//                    historyDoc.append("outStockFinish", true);
//                    historyDoc.append("outStockNumber", outStockNumber);
//                } else {
//                    // 销售订单
//                    Map<String, Object> model = new LinkedHashMap<>();
//                    List<VtuzxMap> FEntity = new ArrayList<>();
//                    for (Map<String, Object> item : items) {
//                        VtuzxMap detailed = new VtuzxMap();
//                        String skuId = VtuzxUtil.getString(item, "sku_id");
//                        double qty = VtuzxUtil.getDouble(item, "qty");
//                        if (qty == 0) {
//                            saveHistory(historyDoc, data, "outStock", true, "出库数量为0，暂存为成功");
//                            return;
//                        }
//                        List<VtuzxMap> materialQuery = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
//                                        "FMATERIALID",
//                                        "FDocumentStatus",
//                                        "F_ora_Base.FNumber",
//                                        "FRefCost"
//                                ),
//                                String.format("FNumber = '%s'", skuId), null, 0, 0);
//                        if (VtuzxUtil.isEmpty(materialQuery)) return;
//                        String supplierId = VtuzxUtil.getString(materialQuery.get(0), "F_ora_Base.FNumber");
//                        String costPrice = VtuzxUtil.getString(materialQuery.get(0), "FRefCost");
//
//                        detailed.append("FMaterialId", new VtuzxMap("FNumber", skuId))
//                                .append("FUnitID", new VtuzxMap("FNumber", "Pcs"))
//                                .append("FRealQty", qty)
//                                .append("FStockID", new VtuzxMap("FNumber", "CK001"))
//                                .append("F_ora_gys", new VtuzxMap("FNumber", supplierId))
//                                .append("F_ora_PURPrice", costPrice);
//                        FEntity.add(detailed);
//                    }
//                    model.put("FCreateOrgId", new VtuzxMap("FNumber", orgId));
//                    model.put("FSaleOrgId", new VtuzxMap("FNumber", orgId));
//                    model.put("FDate", VtuzxUtil.formatYmdF(new Date()));
//                    model.put("FStockOrgId", new VtuzxMap("FNumber", orgId));
//                    model.put("FCustomerID", new VtuzxMap("FNumber", "001"));
//                    model.put("FBillTypeID", new VtuzxMap("FNumber", "XSCKD01_SYS"));
//                    model.put("FSHOPNUMBER", oId);
//                    model.put("FEntity", FEntity);
//                    kingdeeOutStockParam.append("model", model);//金蝶销售出库单
//                    List<VtuzxMap> outStock = kingdeeService.save(client, "SAL_OUTSTOCK", kingdeeOutStockParam);
//                    String outStockNumber = VtuzxUtil.getString(outStock.get(0), "Number");
//                    kingdeeService.submit(client,"SAL_OUTSTOCK", "0", outStockNumber);
//                    kingdeeService.audit(client, "SAL_OUTSTOCK", "0", outStockNumber, "STK_InvCheckResult");
//                    // 履历设定
//                    historyDoc.append("outStockFinish", true);
//                    historyDoc.append("outStockNumber", outStockNumber);
//                }
//
//
//
//
//                //创建客户
//                String shopBuyerId = VtuzxUtil.getString(data, "shop_buyer_id");
//                String receiverMobile = VtuzxUtil.getString(data, "receiver_mobile");
//                List<VtuzxMap> customer = kingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
//                                "FCUSTID",
//                                "FDocumentStatus"
//                        ),
//                        String.format("FNumber = '%s'", receiverMobile), null, 0, 0);
//                if (!VtuzxUtil.isEmpty(customer)) {
//                    String fCUSTID = VtuzxUtil.getString(customer.get(0), "FCUSTID");
//                    String fDocumentStatus = VtuzxUtil.getString(customer.get(0), "FDocumentStatus");
//                    VtuzxMap kingdeeCustomerParam = new VtuzxMap();
//                    Map<String, Object> customerModel = new LinkedHashMap<>();
//                    customerModel.put("FName", shopBuyerId);
//                    customerModel.put("FNumber", receiverMobile);
//                    customerModel.put("FCreateOrgId", new VtuzxMap("FNumber", orgId));
//                    customerModel.put("FCUSTID", fCUSTID);
//                    kingdeeCustomerParam.append("model", customerModel);
//
//                    List<VtuzxMap> customerRes = kingdeeService.save(client, "BD_Customer", kingdeeCustomerParam);
//                    String customerNumber = VtuzxUtil.getString(customerRes.get(0), "Number");
//                    if (!"C".equals(fDocumentStatus)) {
//                        kingdeeService.submit(client,"BD_Customer", "0", customerNumber);
//                        kingdeeService.audit(client, "BD_Customer", "0", customerNumber);
//                    }
//                    // 履历设定
//                    historyDoc.append("customerFinish", true);
//                    historyDoc.append("customerNumber", customerNumber);
//                } else {
//                    VtuzxMap kingdeeCustomerParam = new VtuzxMap();
//                    Map<String, Object> customerModel = new LinkedHashMap<>();
//                    customerModel.put("FName", shopBuyerId);
//                    customerModel.put("FNumber", receiverMobile);
//                    customerModel.put("FCreateOrgId", new VtuzxMap("FNumber", orgId));
//                    kingdeeCustomerParam.append("model", customerModel);
//
//                    List<VtuzxMap> customerRes = kingdeeService.save(client, "BD_Customer", kingdeeCustomerParam);
//                    String customerNumber = VtuzxUtil.getString(customerRes.get(0), "Number");
//                    kingdeeService.submit(client,"BD_Customer", "0", customerNumber);
//                    kingdeeService.audit(client, "BD_Customer", "0", customerNumber);
//                    // 履历设定
//                    historyDoc.append("customerFinish", true);
//                    historyDoc.append("customerNumber", customerNumber);
//                }
//           }
//
//
//
//
//            //收款单
//            for (Map<String, Object> pay: pays) {
//                double payAmount = VtuzxUtil.getDouble(order, "pay_amount");
//                boolean isOrderPay = VtuzxUtil.getBoolean(pay, "is_order_pay");
//                if (isOrderPay) {
//                    VtuzxMap receiveBillParam = new VtuzxMap();
//                    List<VtuzxMap> saleOutStock = kingdeeService.query(client, "AR_RECEIVEBILL", new VtuzxArrayList<>(
//                                    "FID",
//                                    "FDocumentStatus"
//                            ),
//                            String.format("FORDERENTRYID = '%s'", oId), null, 0, 0);
//                    if (!VtuzxUtil.isEmpty(saleOutStock)) {
//                        String fid = VtuzxUtil.getString(saleOutStock.get(0), "FID");
//                        String fDocumentStatus = VtuzxUtil.getString(saleOutStock.get(0), "FDocumentStatus");
//                        Map<String, Object> model = new LinkedHashMap<>();
//                        List<VtuzxMap> FRECEIVEBILLENTRY = new ArrayList<>();
//                        VtuzxMap billEntry = new VtuzxMap();
//                        model.put("FDOCUMENTSTATUS", "C");
//                        model.put("FPAYUNITTYPE", "BD_Customer");
//                        model.put("FPAYUNIT", new VtuzxMap("FNumber", "001"));
//                        model.put("FPAYORGID", new VtuzxMap("FNumber", orgId));
//                        model.put("FSETTLEORGID", new VtuzxMap("FNumber", orgId));
//                        model.put("FCONTACTUNITTYPE", "BD_Customer");
//                        model.put("FCONTACTUNIT", new VtuzxMap("FNumber", "001"));
//                        model.put("FCURRENCYID", new VtuzxMap("FNumber", "PRE001"));
//                        model.put("FBillTypeID", new VtuzxMap("FNUMBER", "SKDLX01_SYS"));
//                        model.put("FDATE", VtuzxUtil.getString(order, "pay_date").substring(0, 10));
//                        model.put("F_ora_salbillno", soId);
//                        model.put("FRECEIVEBILLENTRY", FRECEIVEBILLENTRY);
//                        model.put("FID", fid);
//
//                        billEntry.append("FSETTLETYPEID", new VtuzxMap("FNumber", "JSFS01_SYS"))
//                                .append("FPURPOSEID", new VtuzxMap("FNumber", "SFKYT01_SYS"))
//                                .append("FRECTOTALAMOUNTFOR", payAmount)
//                                .append("FORDERENTRYID", oId);
//                        FRECEIVEBILLENTRY.add(billEntry);
//
//                        receiveBillParam.append("model", model);
//                        //金蝶收款单
//                        List<VtuzxMap> receiveBill = kingdeeService.save(client, "AR_RECEIVEBILL", receiveBillParam);
//                        String receiveBillNumber = VtuzxUtil.getString(receiveBill.get(0), "Number");
//                        if (!"C".equals(fDocumentStatus)) {
//                            kingdeeService.submit(client,"AR_RECEIVEBILL", "0", receiveBillNumber);
//                            kingdeeService.audit(client, "AR_RECEIVEBILL", "0", receiveBillNumber);
//                        }
//                        // 履历设定
//                        historyDoc.append("receiveFinish", true);
//                        historyDoc.append("receiveBillNumber", receiveBillNumber);
//                    } else {
//                        Map<String, Object> model = new LinkedHashMap<>();
//                        List<VtuzxMap> FRECEIVEBILLENTRY = new ArrayList<>();
//                        VtuzxMap billEntry = new VtuzxMap();
//                        model.put("FDOCUMENTSTATUS", "C");
//                        model.put("FPAYUNITTYPE", "BD_Customer");
//                        model.put("FPAYUNIT", new VtuzxMap("FNumber", "001"));
//                        model.put("FPAYORGID", new VtuzxMap("FNumber", orgId));
//                        model.put("FSETTLEORGID", new VtuzxMap("FNumber", orgId));
//                        model.put("FCONTACTUNITTYPE", "BD_Customer");
//                        model.put("FCONTACTUNIT", new VtuzxMap("FNumber", "001"));
//                        model.put("FCURRENCYID", new VtuzxMap("FNumber", "PRE001"));
//                        model.put("FBillTypeID", new VtuzxMap("FNUMBER", "SKDLX01_SYS"));
//                        model.put("FDATE", VtuzxUtil.getString(order, "pay_date").substring(0, 10));
//                        model.put("F_ora_salbillno", soId);
//                        model.put("FRECEIVEBILLENTRY", FRECEIVEBILLENTRY);
//
//                        billEntry.append("FSETTLETYPEID", new VtuzxMap("FNumber", "JSFS01_SYS"))
//                                .append("FPURPOSEID", new VtuzxMap("FNumber", "SFKYT01_SYS"))
//                                .append("FRECTOTALAMOUNTFOR", payAmount)
//                                .append("FORDERENTRYID", oId);
//                        FRECEIVEBILLENTRY.add(billEntry);
//
//                        receiveBillParam.append("model", model);
//                        //金蝶收款单
//                        List<VtuzxMap> receiveBill = kingdeeService.save(client, "AR_RECEIVEBILL", receiveBillParam);
//                        String receiveBillNumber = VtuzxUtil.getString(receiveBill.get(0), "Number");
//                        kingdeeService.submit(client,"AR_RECEIVEBILL", "0", receiveBillNumber);
//                        kingdeeService.audit(client, "AR_RECEIVEBILL", "0", receiveBillNumber);
//                        // 履历设定
//                        historyDoc.append("receiveFinish", true);
//                        historyDoc.append("receiveBillNumber", receiveBillNumber);
//                    }
//                }
//            }
//            saveHistory(historyDoc, data, "outStock", true, "");
//        } catch (Exception e) {
//            saveHistory(historyDoc, data, "outStock", false, e.getMessage());
//        }
//    }



    @Override
    public void syncReturnProduct(Date from, Date to) {
        syncReturnProduct(1, 50, from, to);
    }

    @Override
    public void syncReturnProductHistory(Map<String, Object> history) throws VtuzxException {
        VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
        VtuzxMap kingdeeConfig = kingdeeService.getConfig();
        Document data = VtuzxUtil.getObject(history, "data");
        syncReturnProduct(client, kingdeeConfig, data);
    }

    /**
     * 同步聚水潭退货入库单
     * @param pageIndex 页号
     * @param pageSize 页大小
     * @param from 数据获取时间范围
     * @param to 数据获取时间范围
     */
    private void syncReturnProduct(int pageIndex, int pageSize, Date from, Date to) {
//        _logger.info(String.format("开始同步聚水潭退货单, 第%d页", pageIndex));
//        JushuitanAccount account = jushuitanService.getAccount();
//        try {
//            VtuzxMap returnStockParam = new VtuzxMap();
//            returnStockParam.append("modified_begin", VtuzxUtil.formatYmdHmsF(from));
//            returnStockParam.append("modified_end", VtuzxUtil.formatYmdHmsF(to));
//            returnStockParam.append("page_index", pageIndex);
//            returnStockParam.append("page_size", pageSize);
//            //聚水潭退货入库单
//            VtuzxMap returnProductRes = jushuitanService.callApi(account, "refund.single.query", returnStockParam);
//            List<Map<String, Object>> datas = VtuzxUtil.getObject(returnProductRes, "datas");
//            _logger.info(String.format("获取聚水潭退货单, 第%d页, 共%d单", pageIndex, datas.size()));
//            VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
//            VtuzxMap kingdeeConfig = kingdeeService.getConfig();
//            for (Map<String, Object> data: datas) {
//                syncReturnProduct(client, kingdeeConfig, data);
//            }
//            boolean hasNext = VtuzxUtil.getBoolean(returnProductRes, "has_next");
//            if (hasNext) {
//                _logger.info(String.format("完成同步聚水潭退货单, 第%d页", pageIndex));
//                syncReturnProduct(pageIndex + 1, pageSize, from, to);
//            } else {
//                _logger.info(String.format("完成同步全部聚水潭退货单, 共%d页", pageIndex));
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 同步聚水潭退货入库单
     *
     * @param client 金蝶客户端
     * @param kingdeeConfig 金蝶配置
     * @param data 聚水潭出库单
     */
    private void syncReturnProduct(VtuzxKingdeeCloudClient client, VtuzxMap kingdeeConfig, Map<String, Object> data) {
        String orgId = VtuzxUtil.getString(kingdeeConfig, "orgId");
        // 退货内部单号
        String oId = VtuzxUtil.getString(data, "o_id");
        // 销售订单号
        String soId = VtuzxUtil.getString(data, "so_id");
        _logger.info(String.format("同步聚水潭退货单, 退货单号[%s], 关联订单号[%s]", oId, soId));
        Document historyDoc = integrationHistoryDao.findOne(Criteria.where("orderId").is(oId));
        if (historyDoc == null) historyDoc = new Document("orderId", oId).append("soId", soId);
        try {
            VtuzxMap kingdeeReturnProductParam = new VtuzxMap();
            List<VtuzxMap> FEntity = new ArrayList<>();
            String asDate = VtuzxUtil.getString(data, "as_date");
            String asId = VtuzxUtil.getString(data, "as_id");
            String type = VtuzxUtil.getString(data, "type");
            String status = VtuzxUtil.getString(data, "status");
            String shop_status = VtuzxUtil.getString(data, "shop_status");
            List<Map<String, Object>> items = VtuzxUtil.getObject(data, "items");
            if (("普通退货".equals(type) || "拒收退货".equals(type)) && "Confirmed".equals(status) && "SUCCESS".equals(shop_status)) {
                List<VtuzxMap> returnProduct = kingdeeService.query(client, "SAL_RETURNSTOCK", new VtuzxArrayList<>(
                                "FID",
                                "FDocumentStatus"
                        ),
                        String.format("FSHOPNUMBER = '%s'", asId), null, 0, 0);
                if (!VtuzxUtil.isEmpty(returnProduct)) {
                    String fDocumentStatus = VtuzxUtil.getString(returnProduct.get(0), "FDocumentStatus");
                    String fid = VtuzxUtil.getString(returnProduct.get(0), "FID");
                    for (Map<String, Object> item : items) {
                        String skuId = VtuzxUtil.getString(item, "sku_id");
                        double rQty = VtuzxUtil.getDouble(item, "r_qty");
                        if (rQty == 0) {
                            saveHistory(historyDoc, data, "returnStock", true, "入库数量为0，暂存为成功！");
                            return;
                        }
                        List<VtuzxMap> materialQuery = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                                        "FMATERIALID",
                                        "FDocumentStatus",
                                        "F_ora_Base.FNumber",
                                        "FRefCost"
                                ),
                                String.format("FNumber = '%s'", skuId), null, 0, 0);
                        if (VtuzxUtil.isEmpty(materialQuery)) return;
                        String supplierId = VtuzxUtil.getString(materialQuery.get(0), "F_ora_Base.FNumber");
                        String costPrice = VtuzxUtil.getString(materialQuery.get(0), "FRefCost");
                        VtuzxMap detailed = new VtuzxMap();
                        detailed.append("FMaterialId", new VtuzxMap("FNumber", skuId))
                                .append("FUnitID", new VtuzxMap("FNumber", "Pcs"))
                                .append("FOwnerTypeId", "BD_OwnerOrg")
                                .append("FRealQty", rQty)
                                .append("FOwnerId", new VtuzxMap("FNumber", orgId))
                                .append("FStockId", new VtuzxMap("FNumber", "CK001"))
                                .append("FStockstatusId", new VtuzxMap("FNumber", "KCZT01_SYS"))
                                .append("FReturnType", new VtuzxMap("FNumber", "THLX01_SYS"))
                                .append("FDeliveryDate", asDate.substring(0, 10))
                                .append("F_ora_gys1", new VtuzxMap("FNumber", supplierId))
                                .append("F_ora_Price", costPrice);
                        FEntity.add(detailed);
                    }
                    VtuzxMap model = new VtuzxMap();
                    model.append("FSaleOrgId", new VtuzxMap("FNumber", orgId))
                            .append("FDate", VtuzxUtil.formatYmdF(new Date()))
                            .append("FStockOrgId", new VtuzxMap("FNumber", orgId))
                            .append("FRetcustId", new VtuzxMap("FNumber", "001"))
                            .append("FBillTypeID", new VtuzxMap("FNumber", "XSTHD01_SYS"))
                            .append("FSHOPNUMBER", asId)
                            .append("FID", fid)
                            .append("FEntity", FEntity);
                    kingdeeReturnProductParam.append("model", model);
                    //金蝶销售退货单
                    List<VtuzxMap> returnStockRes = kingdeeService.save(client, "SAL_RETURNSTOCK", kingdeeReturnProductParam);
                    String returnStockNumber = VtuzxUtil.getString(returnStockRes.get(0), "Number");
                    if (!"C".equals(fDocumentStatus)) {
                        kingdeeService.submit(client, "SAL_RETURNSTOCK", "0", returnStockNumber);
                        kingdeeService.audit(client, "SAL_RETURNSTOCK", "0", returnStockNumber);
                    }
                } else {
                    for (Map<String, Object> item : items) {
                        String skuId = VtuzxUtil.getString(item, "sku_id");
                        double rQty = VtuzxUtil.getDouble(item, "r_qty");
                        if (rQty == 0) {
                            saveHistory(historyDoc, data, "returnStock", true, "入库数量为0，暂存为成功！");
                            return;
                        }
                        List<VtuzxMap> materialQuery = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                                        "FMATERIALID",
                                        "FDocumentStatus",
                                        "F_ora_Base.FNumber",
                                        "SubHeadEntity1.FRefCost"
                                ),
                                String.format("FNumber = '%s'", skuId), null, 0, 0);
                        if (VtuzxUtil.isEmpty(materialQuery)) return;
                        String supplierId = VtuzxUtil.getString(materialQuery.get(0), "F_ora_Base.FNumber");
                        String costPrice = VtuzxUtil.getString(materialQuery.get(0), "FRefCost");

                        VtuzxMap detailed = new VtuzxMap();
                        detailed.append("FMaterialId", new VtuzxMap("FNumber", skuId))
                                .append("FUnitID", new VtuzxMap("FNumber", "Pcs"))
                                .append("FOwnerTypeId", "BD_OwnerOrg")
                                .append("FRealQty", rQty)
                                .append("FOwnerId", new VtuzxMap("FNumber", orgId))
                                .append("FStockId", new VtuzxMap("FNumber", "CK001"))
                                .append("FStockstatusId", new VtuzxMap("FNumber", "KCZT01_SYS"))
                                .append("FReturnType", new VtuzxMap("FNumber", "THLX01_SYS"))
                                .append("FDeliveryDate", asDate.substring(0, 10))
                                .append("F_ora_gys1", new VtuzxMap("FNumber", supplierId))
                                .append("F_ora_Price", costPrice);
                        FEntity.add(detailed);
                    }
                    VtuzxMap model = new VtuzxMap();
                    model.append("FSaleOrgId", new VtuzxMap("FNumber", orgId))
                            .append("FDate", VtuzxUtil.formatYmdF(new Date()))
                            .append("FStockOrgId", new VtuzxMap("FNumber", orgId))
                            .append("FRetcustId", new VtuzxMap("FNumber", "001"))
                            .append("FBillTypeID", new VtuzxMap("FNumber", "XSTHD01_SYS"))
                            .append("FSHOPNUMBER", asId)
                            .append("FEntity", FEntity);
                    kingdeeReturnProductParam.append("model", model);
                    //金蝶销售退货单
                    List<VtuzxMap> returnStockRes = kingdeeService.save(client, "SAL_RETURNSTOCK", kingdeeReturnProductParam);
                    String returnStockNumber = VtuzxUtil.getString(returnStockRes.get(0), "Number");
                    kingdeeService.submit(client, "SAL_RETURNSTOCK", "0", returnStockNumber);
                    kingdeeService.audit(client, "SAL_RETURNSTOCK", "0", returnStockNumber);
                }
                _logger.info(String.format("同步聚水潭退货单成功, 退货单号[%s], 关联订单号[%s]", oId, soId));
            }
            saveHistory(historyDoc, data, "returnStock", true, "");
        } catch (Exception e) {
            _logger.warn(String.format("同步聚水潭退货单失败, 退货单号[%s], 关联订单号[%s]", oId, soId));
            saveHistory(historyDoc, data, "returnStock", false, e.getMessage());
        }
    }




    /**
     * 保存处理成功结果履历
     */
    private void saveHistory(Document historyDoc, Map<String, Object> data, String event, boolean success, String message) {
        ObjectId _id = VtuzxUtil.getObject(historyDoc, IVtuzxConst.Key__id);
        if (_id == null) {
            historyDoc.append("event", event);
            historyDoc.append("data", new Document(data));
            historyDoc.append("success", success);
            historyDoc.append("message", message);
            historyDoc.append("retry", 1);
            historyDoc.append("lastRunTime", new Date());
            integrationHistoryDao.insertOne(historyDoc);
        } else {
            integrationHistoryDao.updateByIdRedirect(_id,
                    new Document("$inc", new Document("retry", 1))
                            .append("$set", new Document("success", success)
                                    .append("message", message)
                                    .append("lastRunTime", new Date())));
        }
    }




//    @Override
//    public void SyncPurchaseInStock(Date from, Date to) {
//        subSyncPurchaseInStock(1, 50, from, to);
//    }
//
//    /**
//     * 同步聚水潭采购入库单
//     * @param pageIndex 页号
//     * @param pageSize 页大小
//     * @param from 数据获取时间范围
//     * @param to 数据获取时间范围
//     */
//    private void subSyncPurchaseInStock(int pageIndex, int pageSize, Date from, Date to) {
//        JushuitanAccount account = jushuitanService.getAccount();
//        try {
//            VtuzxMap saleOutStockParam = new VtuzxMap();
//            saleOutStockParam.append("modified_begin", VtuzxUtil.formatYmdHmsF(from));
//            saleOutStockParam.append("modified_end", VtuzxUtil.formatYmdHmsF(to));
//            saleOutStockParam.append("page_index", pageIndex);
//            saleOutStockParam.append("page_size", pageSize);
//            //聚水潭采购入库订单
//            VtuzxMap outStockRes = jushuitanService.callApi(account, "purchasein.query", saleOutStockParam);
//            List<Map<String, Object>> datas = VtuzxUtil.getObject(outStockRes, "datas");
//            VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
//            VtuzxMap kingdeeConfig = kingdeeService.getConfig();
//            for (Map<String, Object> data: datas) {
//                syncKingdeePurchaseInStock(account, client, kingdeeConfig, data);
//            }
//            boolean hasNext = VtuzxUtil.getBoolean(outStockRes, "has_next");
//            if (hasNext) {
//                subSyncPurchaseInStock(pageIndex + 1, pageSize, from, to);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

//    /**
//     * 同步聚水潭采购入库单
//     *
//     * @param client 金蝶客户端
//     * @param kingdeeConfig 金蝶配置
//     * @param data 聚水潭出库单
//     */
//    private void syncKingdeePurchaseInStock(JushuitanAccount account, VtuzxKingdeeCloudClient client, VtuzxMap kingdeeConfig, Map<String, Object> data) {
//        String orgId = VtuzxUtil.getString(kingdeeConfig, "orgId");
//        // 出库内部单号
//        String oId = VtuzxUtil.getString(data, "o_id");
//        // 销售订单号
//        String soId = VtuzxUtil.getString(data, "so_id");
//        _logger.info(String.format("同步聚水潭采购入库单, 入库单号[%s], 采购单号[%s]", oId, soId));
//        Document historyDoc = integrationHistoryDao.findOne(Criteria.where("orderId").is(oId));
//        if (historyDoc == null) historyDoc = new Document("orderId", oId).append("soId", soId);
//        try {
//            List<VtuzxMap> purchaseInStock = kingdeeService.query(client, "STK_InStock", new VtuzxArrayList<>(
//                            "FID",
//                            "FDocumentStatus"
//                    ),
//                    String.format("F_ora_jstbillno = '%s'", soId), null, 0, 0);
//            if (!VtuzxUtil.isEmpty(purchaseInStock)) {
//                String fDocumentStatus = VtuzxUtil.getString(purchaseInStock.get(0), "FDocumentStatus");
//                String fid = VtuzxUtil.getString(purchaseInStock.get(0), "FID");
//                syncPurchaseInStock(client, kingdeeConfig, data, historyDoc, fid, fDocumentStatus);
//            } else {
//                syncPurchaseInStock(client, kingdeeConfig, data, historyDoc, "", "");
//            }
//            _logger.info(String.format("同步聚水潭采购入库单成功, 入库单号[%s], 采购单号[%s]", oId, soId));
//            saveHistory(historyDoc, data, "purchaseInStock", true, "");
//        } catch (Exception e) {
//            _logger.warn(String.format("同步聚水潭采购入库单失败, 入库单号[%s], 采购单号[%s]", oId, soId));
//            saveHistory(historyDoc, data, "purchaseInStock", false, e.getMessage());
//        }
//    }

    private void syncPurchaseInStock(VtuzxKingdeeCloudClient client, VtuzxMap kingdeeConfig, Map<String, Object> data, Document historyDoc, String fid, String fDocumentStatus) throws Exception {
        String orgId = VtuzxUtil.getString(kingdeeConfig, "orgId");
        // 销售订单号
        String soId = VtuzxUtil.getString(data, "so_id");
        List<Map<String, Object>> items = VtuzxUtil.getObject(data, "items");

        VtuzxMap kingdeePurchaseInStockParam = new VtuzxMap();
        Map<String, List<VtuzxMap>> supplierMap = new HashMap<>();
        for (Map<String, Object> item : items) {
            String skuId = VtuzxUtil.getString(item, "sku_id");
            double qty = VtuzxUtil.getDouble(item, "qty");
            if (qty == 0) {
                saveHistory(historyDoc, data, "purchaseInStock", true, "入库数量为0，暂存为成功！");
                return;
            }
            List<VtuzxMap> materialQuery = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                            "FMATERIALID",
                            "FDocumentStatus",
                            "F_ora_Base.FNumber",
                            "FRefCost"
                    ),
                    String.format("FNumber = '%s'", skuId), null, 0, 0);
            if (VtuzxUtil.isEmpty(materialQuery)) return;
            String supplierId = VtuzxUtil.getString(materialQuery.get(0), "F_ora_Base.FNumber");
            if (VtuzxUtil.isEmpty(supplierId)) continue;
            String fRefCost = VtuzxUtil.getString(materialQuery.get(0), "FRefCost");
            VtuzxMap detailed = new VtuzxMap();
            detailed.append("FMaterialId", new VtuzxMap("FNumber", skuId))
                    .append("FUnitID", new VtuzxMap("FNumber", "Pcs"))
                    .append("FPriceUnitID", new VtuzxMap("FNumber", "Pcs"))
                    .append("FStockId", new VtuzxMap("FNumber", "CK001"))
                    .append("FTaxNetPrice", fRefCost) //净价
                    .append("FRealQty", qty);
            List<VtuzxMap> materialList = supplierMap.computeIfAbsent(supplierId, k -> new ArrayList<>());
            materialList.add(detailed);
        }
        for(String supplierId: supplierMap.keySet()) {
            List<VtuzxMap> detailList = supplierMap.get(supplierId);
            VtuzxMap model = new VtuzxMap();
            model.append("FSaleOrgId", new VtuzxMap("FNumber", orgId))
                    .append("FDate", VtuzxUtil.formatYmdF(new Date()))
                    .append("FPurchaseOrgId", new VtuzxMap("FNumber", orgId))
                    .append("FBillTypeID", new VtuzxMap("FNumber", "RKD01_SYS"))
                    .append("F_ora_jstbillno", soId) //聚水潭单据号
                    .append("FSupplierId", new VtuzxMap("FNumber", supplierId)) //供应商
                    .append("FInStockEntry", detailList); //明细
            if (!VtuzxUtil.isEmpty(fid)) {
                model.append("FID", fid);
            }
            kingdeePurchaseInStockParam.append("model", model);
            //金蝶采购入库单
            List<VtuzxMap> purchaseInStockRes = kingdeeService.save(client, "STK_InStock", kingdeePurchaseInStockParam);
            String purchaseInStockNumber = VtuzxUtil.getString(purchaseInStockRes.get(0), "Number");
            if (!"C".equals(fDocumentStatus)) {
                kingdeeService.submit(client, "STK_InStock", "0", purchaseInStockNumber);
                kingdeeService.audit(client, "STK_InStock", "0", purchaseInStockNumber);
            }
        }
    }
}
